% ---------------------------------------------------
% @doc 用户信息处理器.
% ---------------------------------------------------
-module(msgpack_handler).
-include("cloap_record.hrl").

-export([init/2]).
-export([
  allowed_methods/2,
  content_types_provided/2,
  resource_exists/2
]).

-export([
         news_index/2,
         todo_index/2
]).


init(Req, Opts) ->
	{cowboy_rest, Req, Opts}.

msgtype(Req) ->
    MsgType = cowboy_req:binding(msgtype, Req),
    lager:info("msgtype: ~p", [MsgType]),
    case MsgType of
        <<"todo">> -> todo_index;
        _ -> news_index
    end.
            


allowed_methods(Req, State) ->
  {
    [<<"GET">>, <<"POST">>, <<"HEAD">>, <<"OPTIONS">>],
    Req, State
  }.


content_types_provided(Req, State) ->
    Req1 = cowboy_req:set_resp_header(<<"access-control-allow-methods">>, <<"GET, OPTIONS">>, Req),
    Req2 = cowboy_req:set_resp_header(<<"access-control-allow-origin">>, <<"*">>, Req1),
    {[
      {<<"application/json">>, msgtype(Req)}
     ], Req2, State}.


resource_exists(Req, _State) ->
  {true, Req, news_index}.


news_index(Req, State) ->
    {jsx:encode(newspack_api:list()), Req, State}.

todo_index(Req, State) ->
    SpiderUsers = cloap_handler:handle("spider.user.index", []),
    Result =
        [ #{name => proplists:get_value(name, X), account => proplists:get_value(login, X),
            contents => cloap_handler:handle("todo.index", [{<<"login">>, proplists:get_value(login, X)}])}
          || X <- SpiderUsers ],
    {jsx:encode(Result), Req, State}.
            

